<template>
  <div class="user">
    <div class="main-title">用户管理</div>
    <el-card
      class="box-card"
      v-loading="isLoading">
      <!-- 头部表单 -->
      <div slot="header" class="clearfix">
        <el-form
          ref="form"
          :model="query"
          label-position="left"
          label-width="60px"
          inline
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input
              v-model="query.username"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="学号"
            prop="_id"
          >
            <el-input v-model="query._id"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click.native="handleQuery"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click.native="handleReset">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click.native="handleCreate"
            >新建用户</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 底部表格 -->
      <el-table
        :data="users"
        stripe
      >
        <el-table-column
          align="center"
          prop="_id"
          label="学号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="username"
          label="姓名"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="avatarUrl"
          label="头像"
        >
          <template slot-scope="scope">
            <el-image
              :src="scope.row.avatarUrl"
              :alt="scope.row.username"
              fit="cover"
              :preview-src-list="[scope.row.avatarUrl]"
              style="width: 60px; height: 75px;"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="bookCount"
          label="借阅数目"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="status"
          label="借阅状态"
        >
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.status === 0"
              type="info"
            >未借阅</el-tag>
            <el-tag
              v-else-if="scope.row.status === 1"
              type="success"
            >正常</el-tag>
            <el-tag
              v-else
              type="danger"
            >超时</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="permission"
          label="用户状态"
        >
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.permission"
              type="success"
            >正常</el-tag>
            <el-tag
              v-else
              type="danger"
            >封禁</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="300"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button @click.native="handleEdit(scope.row)">编辑</el-button>
            <el-button
              @click.native="handleBan(scope.row)"
              v-if="scope.row.permission"
              type="danger"
            >封禁</el-button>
            <el-button
              @click.native="handleBan(scope.row)"
              v-else
              type="success"
            >解封</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页栏 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="pager.pageSize"
          :current-page="pager.curPage"
          :total="pager.total"
          @current-change="handlePageChange">
        </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getUsers, queryUser, banUser } from '@/services/user'
export default {
  name: 'User',
  data () {
    return {
      // 查询参数
      query: {
        username: '',
        _id: null
      },
      // 显示的用户列表
      users: [],
      // 服务器拉取的源数据
      originUsers: [],
      // 分页数据
      pager: {
        // 数据总条数
        total: 0,
        // 每页显示数据条数,
        pageSize: 5,
        // 当前页
        curPage: 1
      },
      // 控制加载状态
      isLoading: false
    }
  },
  created () {
    this.loadUsers()
  },
  methods: {
    // 查询和分页（公共部分）
    async queryAndPage () {
      this.isLoading = true
      const params = {
        pageSize: this.pager.pageSize,
        curPage: this.pager.curPage,
        _id: this.query._id,
        username: this.query.username
      }
      if (!params._id && !params.username) {
        // 如果查询条件全空，默认拉取所有用户信息
        this.loadUsers()
      } else {
        const { data } = await queryUser(params)
        if (data.data.length > 0) {
          const users = []
          data.data.forEach((item) => {
            users.push(JSON.parse(item))
          })
          this.users = users
          // 这里需要获取返回的符合条件的总长度
          // 接口要求 pageSize 为 null 时就默认返回全部符合条件的数据
          params.pageSize = null
          const lengthData = await queryUser(params)
          this.pager.total = lengthData.data.data.length
        } else {
          this.users = []
          this.$message.info('找不到符合条件的用户！')
          this.pager.total = 0
        }
        this.isLoading = false
        this.isPaging = false
      }
    },
    // 查询
    async handleQuery () {
      this.pager.curPage = 1
      this.queryAndPage()
    },
    // 编辑用户信息
    handleEdit (rowData) {
      this.$router.push({
        name: 'edit-user',
        params: {
          id: rowData._id
        }
      })
    },
    // 封禁用户
    async handleBan (rowData) {
      const userData = {
        _id: rowData._id,
        permission: !rowData.permission
      }
      // 发请求然后刷新
      const { data } = await banUser(userData)
      if (data.errcode === 0) {
        this.$message.success(`${userData.permission ? '解封' : '封禁'}成功！`)
        this.queryAndPage()
      } else {
        this.$message.error(`${userData.permission ? '解封' : '封禁'}失败！`)
      }
    },
    // 新建用户
    handleCreate () {
      // 路由跳转
      this.$router.push({
        name: 'create-user'
      })
    },
    // 加载所有用户
    async loadUsers () {
      if (this.isPaging && !this.isLoading) return
      this.isPaging = true
      this.isLoading = true
      const users = []
      const params = {
        pageSize: this.pager.pageSize,
        curPage: this.pager.curPage,
        _id: this.query._id,
        username: this.query.username
      }
      const { data } = await getUsers(params)
      if (data.errcode === 0) {
        data.data.forEach(item => {
          const user = JSON.parse(item)
          users.push(user)
        })
        this.users = users
        data.collectionInfo.collections.forEach(item => {
          if (item.name === 'users') {
            this.pager.total = item.count
          }
        })
      } else {
        this.$message.error('拉取用户列表出错，请重新登录')
        this.$router.push({
          name: 'login'
        })
      }
      this.isPaging = false
      this.isLoading = false
    },
    // 分页的控制操作
    async handlePageChange (toPage) {
      this.pager.curPage = toPage
      // 避免重复发送分页请求
      await this.queryAndPage()
    },
    // 表单重置
    handleReset () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('~@/styles/my-button.scss');
@import url('~@/styles/my-form.scss');
</style>
